﻿using IdentityModel;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace Core.FrameWork.Commons.App.HttpContextUser
{
    /// <summary>
    /// Http 用户Httpcontext
    /// </summary>
    public class HttpContextUser : IHttpContextUser
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        public HttpContextUser(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
        public IEnumerable<Claim> GetClaimsIdentity(string ClaimType)
        {
            return (from item in _httpContextAccessor.HttpContext.User.Claims
                    where item.Type == ClaimType
                    select item);
        }

        public string GetToken()
        {
            return _httpContextAccessor.HttpContext.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
        }

        public AspNetUser GetUserInfo()
        {
            return new AspNetUser()
            {
                Id = GetClaimsIdentity(JwtClaimTypes.Id).FirstOrDefault()?.Value,
                Name = GetClaimsIdentity(JwtClaimTypes.Name).FirstOrDefault()?.Value,
                Role = GetClaimsIdentity(JwtClaimTypes.Role).FirstOrDefault()?.Value,
                Token = GetToken()
            };

        }

        public List<string> GetUserInfoFromToken(string ClaimType)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            if (!string.IsNullOrEmpty(GetToken()))
            {
                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(GetToken());

                return (from item in jwtToken.Claims
                        where item.Type == ClaimType
                        select item.Value).ToList();
            }
            else
            {
                return new List<string>() { };
            }
        }

        public bool IsAuthenticated()
        {
            return _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated;
        }
    }
}
